﻿Public Class Clientes

    Private _indic As UInt16 = 1
    Private _nuevo As Boolean = False
    Private EnlaceTabla As New BindingSource
    Private cambios, notDataSaved As Boolean
    Private totalCampos As UInt16

    WriteOnly Property indic() As UInt16
        Set(ByVal Value As UInt16)
            _indic = Value
        End Set
    End Property

    WriteOnly Property nuevo() As Boolean
        Set(ByVal Value As Boolean)
            _nuevo = Value
        End Set
    End Property

    Private Sub Clientes_FormClosing(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
        e.Cancel = notDataSaved
    End Sub

    Private Sub Clientes_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Dim a, b, c, d As NumberOnlyTextbox
        a = New NumberOnlyTextbox(Me.CCCAgencia, True, True, Nothing)
        b = New NumberOnlyTextbox(Me.CCCBanco, False, False, Nothing)
        c = New NumberOnlyTextbox(Me.CCCControl, False, False, Nothing)
        d = New NumberOnlyTextbox(Me.CCCCuenta, False, False, Nothing)

        If Not _nuevo Then EnlaceTabla.DataSource = _
           DataAccess.GetRecords("SELECT * FROM Clientes WHERE NoCliente=" & _indic.ToString, CommandType.Text)
        Enlaces()
    End Sub

    Private Sub cleanForm()
        Dim i As Integer

        For i = 0 To TabClient.TabPages.Count - 1
            For Each Objeto As Control In Me.TabClient.TabPages(i).Controls
                Objeto.DataBindings.Clear()
                If TypeOf Objeto Is TextBox Then Objeto.Text = ""
            Next
        Next
        TabCliente.Select()
        CliNum.DataBindings.Clear()
        CliNum.Text = ""
        Enlaces()
    End Sub

    Public Sub updateFormasPago()
        With CliFrmPago
            .DataSource = DataAccess.GetRecords("SELECT * FROM FormasPago ORDER BY idFP", CommandType.Text)
            .DisplayMember = "Descripcion"
            .ValueMember = "idFP"
            If Not _nuevo Then .DataBindings.Add("SelectedValue", EnlaceTabla, "FormaPago")
        End With
    End Sub

    Public Sub updateRepresentantes()
        With CliRepresentante
            .DataSource = DataAccess.GetRecords("SELECT * FROM Representantes ORDER BY idRepresentante", CommandType.Text)
            .DisplayMember = "Nombre"
            .ValueMember = "idRepresentante"
            If Not _nuevo Then .DataBindings.Add("SelectedValue", EnlaceTabla, "Representante")
        End With
    End Sub

    Public Sub updateIVA()
        'With CliIVA
        '    .DataSource = DataAccess.GetRecords("SELECT * FROM IVA ORDER BY idIVA", CommandType.Text)
        '    .DisplayMember = "Nombre"
        '    .ValueMember = "idIVA"
        '    If Not _nuevo Then .DataBindings.Add("SelectedValue", EnlaceTabla, "IVA")
        'End With
    End Sub

    Private Sub Enlaces()
        Dim i As Integer
        updateFormasPago()
        updateRepresentantes()
        updateIVA()
        totalCampos = 0
        For i = 0 To TabClient.TabPages.Count - 1
            TabClient.TabPages(i).Show()
            For Each Objeto As Control In Me.TabClient.TabPages(i).Controls
                If TypeOf Objeto Is TextBox Then
                    If Not _nuevo Then Objeto.DataBindings.Add("Text", EnlaceTabla, Objeto.Tag)
                    AddHandler Objeto.TextChanged, AddressOf Cliente_TextChanged
                    totalCampos += 1
                End If
            Next
        Next
        totalCampos += 3
        AddHandler CliFrmPago.TextChanged, AddressOf Cliente_TextChanged
        AddHandler CliRepresentante.TextChanged, AddressOf Cliente_TextChanged
        AddHandler CliIVA.TextChanged, AddressOf Cliente_TextChanged
        If Not _nuevo Then
            CliNum.DataBindings.Add("Text", EnlaceTabla, "NoCliente")
        End If

    End Sub

    Private Sub Cliente_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
        cambios = True
        BtnClear.Enabled = IIf(_nuevo, True, False)
        BtnSave.Enabled = Convert.ToBoolean(CliRazonSocial.Text.Length * sender.Text.Length)
    End Sub

    Private Sub ButnSalir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        If cambios Then
            Dim msg = "¿Desea salir del módulo Clientes?"
            Dim title = "¡Advertencia!"
            Dim style = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or _
                        MsgBoxStyle.Critical
            notDataSaved = IIf(MsgBox(msg, style, title) = MsgBoxResult.Yes, False, True)
        End If
        Me.Close()
        If Not notDataSaved Then Me.Dispose()
    End Sub

    Private Sub BtnSave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnSave.Click
        insertUpdate(_nuevo)
    End Sub

    Private Sub insertUpdate(ByVal newClient As Boolean)
        Dim Valores(totalCampos - 1) As String
        Dim Campos(totalCampos - 1) As String
        'Dim camposValores As New ArrayList()
        Dim i As Integer
        Dim k As UInt16 = 0
        Dim procName As String = IIf(newClient, "insertCliente", "updateCliente")

        If Not newClient Then
            ReDim Valores(totalCampos)
            ReDim Campos(totalCampos)
            Campos.SetValue("@" + CliNum.Tag, k)
            Valores.SetValue(CliNum.Text, k)
            k += 1
        End If
        For i = 0 To TabClient.TabPages.Count - 1
            For Each Objeto As Control In Me.TabClient.TabPages(i).Controls
                If TypeOf Objeto Is TextBox Or TypeOf Objeto Is DateTimePicker Then
                    Campos.SetValue("@" + Objeto.Tag, k)
                    Valores.SetValue(Objeto.Text, k)
                    k += 1
                ElseIf TypeOf Objeto Is System.Windows.Forms.ComboBox Then
                    Dim nuevoCombo As New ComboBox
                    nuevoCombo = Objeto
                    Campos.SetValue("@" + nuevoCombo.Tag, k)
                    Try
                        Valores.SetValue(nuevoCombo.SelectedValue.ToString, k)
                    Catch e As Exception
                        MessageBox.Show(e.Message)
                        Valores.SetValue("", k)
                    End Try
                    k += 1
                    nuevoCombo = Nothing
                End If
            Next
        Next
        If DataAccess.InsertNewRecord(Campos, Valores, procName) = -1 Then
            MessageBox.Show("Error al guardar registro de Cliente")
        Else
            Dim frm
            For Each frm In My.Application.OpenForms
                Console.WriteLine(frm.name)
                If frm.name = "ListaClientes" Then frm.refrescarDataGrid()
            Next
            frm = Nothing
            If newClient Then
                cleanForm()
            Else
                notDataSaved = False
                Me.Close()
                Me.Dispose()
            End If
        End If
    End Sub

    Private Sub BtnClear_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles BtnClear.Click
        cleanForm()
    End Sub

    Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
        With FormasPago
            .ShowDialog()
        End With
    End Sub

    Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        Dim myRepr As New Representantes
        With myRepr
            .callFromForm = True
            .nuevo = True
            .ShowDialog()
        End With
    End Sub

    Protected Overrides Sub Finalize()
        MyBase.Finalize()
    End Sub
End Class